<template>
    <el-dialog v-model="dialogVisible" custom-class="label-dialog-box" :title="title" width="900px" :append-to-body="true"
        :before-close="cancelHandel">
        <div v-loading="loading">
            <div class="el-dialog-body">
                <section class="dialog-content-box">
                    <div class="content-seach">
                        <el-row>
                            <el-col :span="14">
                                <el-input v-model="keyword" placeholder="请输入标签名称或标签组名称" :prefix-icon="Search" clearable
                                    @keypress.enter="searchTagList" />
                                <el-button type="primary" class="search-button" @click="searchTagList">查询</el-button>
                            </el-col>
                            <el-col :span="10" style="text-align: right">
                                <div class="refresh">
                                    <el-icon class="icon">
                                        <refresh-right />
                                    </el-icon>
                                    <span @click="refreshTagList">刷新数据</span>
                                </div>
                            </el-col>
                        </el-row>
                    </div>
                    <div class="content-label-list">
                        <div class="content-label-item" v-for="item in labels" :key="item.Id">
                            <div class="content-label-title">{{ item.Name }}</div>
                            <div class="content-label-tags">
                                <el-tag v-for="tagItem in item.Labels" :key="tagItem.Id"
                                    :effect="isSelected(tagItem) ? 'light' : 'plain'" @click="handleChangeSelect(tagItem)">
                                    {{ tagItem.Name }}
                                </el-tag>
                            </div>
                        </div>
                    </div>
                </section>

                <div class="dialog-content-right">
                    <div class="right-title">
                        <div>
                            <span>已选：</span>
                            <span class="span">{{ selectedMap.size }}个标签</span>
                        </div>
                        <div><span class="active" @click="clearSelected">清空</span></div>
                    </div>

                    <div class="choose-tag zw-common-scrollbar">
                        <el-tag v-for="(tag, index) in selectedMap.values()" :key="tag.Id" :type="tag.isDelete ? 'info' : ''" closable @close="removeTags(tag)">
                            {{ tag.Name }}
                        </el-tag>
                    </div>
                </div>
            </div>
            <div class="dialog-footer">
                <div>
                    <el-button @click="cancelHandel">取消</el-button>
                    <el-button type="primary" @click="submitHandel">保存</el-button>
                </div>
            </div>
        </div>
    </el-dialog>
</template>

<script setup>
import { reactive, ref, onMounted, computed, watch, nextTick } from "vue";
import { ElMessage, ElLoading } from "element-plus";
import { Search } from "@element-plus/icons-vue";
import { getTagList, refreshTagDataList } from "../../../ajax/api/common";

const title = ref("选择标签");

const props = defineProps({
    modelValue: {
        type: Boolean,
        default: false
    },
    selectedMember: {
        type: Array,
        default: () => []
    },
})

const emit = defineEmits(["update:modelValue", "submit"]);

/* ----------------------------弹窗显隐-start---------------------------- */
const open = async (selectedList = []) => {
    emit('update:modelValue', true)
    await nextTick()
    setSelectMap(selectedList);
}

/** 弹窗展示 */
const dialogVisible = computed({
    get() {
        return props.modelValue
    },
    set(value) {
        emit('update:modelValue', value)
    }
})

/* ----------------------------弹窗显隐-end---------------------------- */

/* ----------------------------搜索标签-start---------------------------- */
const labels = reactive([]);

const searchParams = reactive({
    keyword: '',
});

const keyword = ref('')

watch(
    dialogVisible,
    (val) => {
        // 打开的情况下并且是接口已经加载完的情况下才会在此刷新
        // 这么做是为了防止接口过长时间，点击窗口又会重新调用接口的问题
        if (val && !loading.value) {
            selectedMap.clear()
            searchParams.keyword = ''
            keyword.value = ''
            getTagsListData()
        }
    },
    { deep: true, immediate: true }
);

const loading = ref(false)
/**
 * 查询标签列表数据
 */
const getTagsListData = async (getTagApi = getTagList) => {
    try {
        loading.value = true
        const tagList = await getTagApi(searchParams);
        if (tagList && !tagList.length) {
            ElMessage.warning("未收到数据，可能未同步企微数据，请手动同步");
        }
        labels.splice(0);
        labels.push(...tagList);
    } finally {
        loading.value = false
    }
}

/**
 * 输入完内容点击查询搜索
 */
const searchTagList = () => {
    searchParams.keyword = keyword.value;
    getTagsListData()
}

/**
 * 刷新标签列表
 */
const refreshTagList = () => {
    getTagsListData(refreshTagDataList)
}
/* ----------------------------搜索标签-end---------------------------- */


/* ----------------------------选择-start---------------------------- */
const selectedMap = reactive(new Map())

/**
 * 页面打开时会设置默认选中的
 * @param {Array} selectedList 需要设置成默认选中的数组，Id和Name
 */
const setSelectMap = (selectedList) => {
    if (Array.isArray(selectedList) && selectedList.length) {
        selectedList.forEach(item => {
            selectedMap.set(item.Id, item)
        })
    }
}

/** 是否选中当前标签 */
const isSelected = (tagItem) => {
    return selectedMap.has(tagItem.Id)
}

const handleChangeSelect = (tagItem) => {
    // 已经选中的情况下点击无效
    if (selectedMap.has(tagItem.Id)) {
        selectedMap.delete(tagItem.Id);
        return
    }

    selectedMap.set(tagItem.Id, tagItem)
}
/**
 * 清空所有的选中项
 */
const clearSelected = () => {
    selectedMap.clear()
}

/**
 * 删除选中的当前的tag
 * @param {id, name} tagItem 当前的tag
 */
const removeTags = (tagItem) => {
    selectedMap.delete(tagItem.Id);
}
/* ----------------------------选择-end---------------------------- */

const cancelHandel = () => {
    emit("update:modelValue", false);
};
const submitHandel = () => {
    const selectList = Array.from(selectedMap.values());
    if (!selectList.length) {
        ElMessage.warning('请选择标签')
        return
    }
    emit("update:modelValue", false);
    emit("submit", selectList);
};

defineExpose({
    open
});
</script>

<style lang="scss" scoped>
.el-dialog-body {
    display: flex;

    .dialog-content-box {
        width: 600px;
        padding-right: 20px;

        .content-seach {
            margin-bottom: 20px;
            font-size: 14px;
            font-family: STHeitiSC-Light, STHeitiSC;
            color: #969696;

            .el-row {
                display: flex;
                align-items: center;

                >.el-col:first-child {
                    display: flex;
                    align-items: center;
                }
            }

            .search-button {
                margin-left: 16px;
            }

            .active {
                color: var(--el-color-primary);
                cursor: pointer;

                a {
                    color: var(--el-color-primary);
                    text-decoration: none;
                }
            }

            .refresh {
                cursor: pointer;
                display: inline-block;
                line-height: 19px;
                margin-right: 10px;

                .icon {
                    vertical-align: middle;
                    font-size: 16px;
                }

                span {
                    vertical-align: middle;
                }

                &:hover {
                    color: var(--el-color-primary);

                    .icon {
                        color: var(--el-color-primary);
                    }
                }
            }
        }
    }

    .dialog-content-right {
        width: 300px;
        padding: 0px 20px;
        border-left: 1px solid #eaeaea;

        .right-title {
            display: flex;
            justify-content: space-between;
            height: 3px;
            line-height: 32px;

            .active {
                color: var(--el-color-primary);
                cursor: pointer;
            }
        }

        .choose-tag {
            margin-top: 50px;
            max-height: 356px;
            display: flex;
            flex-wrap: wrap;
            gap: 6px;
            overflow-y: auto;
            overflow-x: hidden;
        }
    }
}

.dialog-footer {
    border-top: 1px solid #dcdfe6;
    padding-top: 16px;
    padding-right: 20px;
    margin: 0 -20px;
    display: flex;
    justify-content: end;
    align-items: center;
}

.content-label-list {
    height: 460px;
    overflow-y: auto;

    .content-label-item {
        margin-bottom: 12px;

        .content-label-title {
            font-size: 14px;
            color: #777;
        }

        .content-label-tags {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            margin-top: 8px;

            :deep(.el-tag.el-tag--plain) {
                border-color: #ccc;
                color: #666;
            }
        }


        .el-tag {
            padding: 12px;
            cursor: pointer;
        }
    }
}
</style>
